package cn.study.zgm.nettyall.selector.bio;

import cn.study.zgm.nettyall.channel.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * packageName cn.study.zgm.nettyall.selector.bio
 *
 * @author 你的名字
 * @version JDK 8
 * @className BolckingServer (此处以class为例)
 * @date 2025/2/25
 * @description TODO
 */
@Slf4j
public class BolckingServer {
    public static void main(String[] args) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocate(32);

        // 1.创建服务器端
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 2.绑定监听端口
        ssc.bind(new InetSocketAddress(8081));
        // 3.创建一个channel集合，用于存放channel
        List<SocketChannel> channelList = new ArrayList<>();
        while (true){
            log.info("通道开始连接>>>>>>>>>>>>>>>");
            // 4.accept建立与客户端的连接，SocketChannel用来和客户端之间通信
            final SocketChannel channel = ssc.accept(); //阻塞式，线程会停止，需要等到来自客户端的连接，才会走下一步
            log.info("通道已经连接>>>>>>>>>>>>>>>");

            channelList.add(channel);

            //遍历通道，获取客户端发送的消息
            for (SocketChannel socketChannel : channelList) {
                // 5.接收客户端发送的数据
                log.error("channel开始读取数据>>>>>>>>>>>>>>>>");
                socketChannel.read(buffer); // 阻塞方法，线程停止运行
                buffer.flip();// 切换为读模式
                ByteBufferUtil.debugRead(buffer);
                buffer.clear();// 读取完，切换为写模式，方便下一次channel写入
                log.error("channel读取数据结束>>>>>>>>>>>>>>>>");
            }
        }
    }
}
